<?php
/**
 * Created by PhpStorm.
 * User: MI
 * Date: 2018/10/12
 * Time: 10:13
 */

namespace App\Services;


use GuzzleHttp\Client;
use GuzzleHttp\Exception\RequestException;

class WeiHouService
{
    /**
     * @var Client
     */
    protected $sender;
    /**
     * @var array 配置文件
     */
    private $config = [];
    /**
     *
     * @var string
     */
    public $domain;
    /**
     * @var array
     */
    protected $headers = [];
    private $parameters = [];

    /**
     * WeiHouService constructor.
     * @param $config
     */
    public function __construct($config)
    {
        $this->config = $config;
        $this->domain = $config['domain'];
        $this->getCommonParameters();
    }
    /**
     *
     * @return Client
     */
    public function getSender()
    {
        if (!$this->sender) {
            $this->sender = new Client();
        }
        return $this->sender;
    }

    /**
     * 获取公共参数
     */
    public function getCommonParameters(){
        $this->parameters = [
            'auth_type' => 2,
            'app_key'=>$this->config['app_key'],
            'signed_at'=> time()
        ];
    }
    /**
     * @param array $headers
     */
    public function getHeaders()
    {
        return $this->headers;
    }

    /**
     * @param $username 用户名
     * @param $password 密码
     */
    public function addRegisterThirdUser($username,$password){
        $params = array_merge($this->parameters,['third_user_id'=>$username,'pass'=>$password]);
        $params['sign'] = $this->getSign($params);
//        dd($form_params);
//        dd($this->domain . 'user/register');
        $response = $this->request('POST', $this->domain . 'user/register', [
            'form_params' => $params
        ]);
        return $response;
    }

    /**
     * 获取
     * @param $params
     * @return string
     */
    public function getSign($params){
        $params['app_key'] = $this->config['app_key'];
        // 按参数名升序排列
        ksort($params);
        // 将键值组合
        array_walk($params,function(&$value,$key){
            $value = $key . $value;
        });
        // 拼接,在首尾各加上$secret_key,计算MD5值
        $sign = md5($this->config['api_secret'] . implode('',$params) . $this->config['api_secret']);
        return $sign;
    }


    /**
     * @param $method
     * @param $url
     * @param array $options
     * @return Response
     */
    public function request($method, $url, array $options = [])
    {
        try {
            $sender = $this->getSender();
            $options = array_merge($options, ['headers' => $this->getHeaders()]);
            $response = $sender->request($method, $url, $options);
            $successResult = new Response($response);
            return $successResult;
        } catch (RequestException $e) {
            $errorResult = new Response($e->getResponse(), false);
            return $errorResult;
        }
    }
}